package com.codewsq.java;

import org.junit.Test;

import java.util.Random;

public class NewInstanceTest {

    @Test
    public void test() throws IllegalAccessException, InstantiationException {
        Class<Person> clazz = Person.class;
        /*
         * newInstance():此方法可以为 调用它的运行时类创建一个对象，内部调用了运行时类的空仓构造器
         *
         * 成功运行此方法的前提： 运行时类必须提供 public修饰的无参构造方法
         *
         * 在javabean中要求提供一个public的无参构造器的原因：
         * 1. 便于通过反射创建该运行时类的对象
         * 2. 便于子类继承此运行时类时，默认调用super()时，保证父类有无参构造器
         * */
        Person person = clazz.newInstance();
        System.out.println(person);
    }


    @Test
    public void test2() {
        for (int i = 0; i < 20; i++) {
            int num = new Random().nextInt(3);// 0 1 2
            String classPath = null;
            switch (num) {
                case 0:
                    classPath = "com.codewsq.java.ClassloaderTest";
                    break;
                case 1:
                    classPath = "com.codewsq.java.NewInstanceTest";
                    break;
                case 2:
                    classPath = "com.codewsq.java.ReflectionTest";
                    break;
            }

            Object instance = getInstance(classPath);
            System.out.println(instance);
        }
    }

    /**
     * 根据全类名称创建对应的对象
     *
     * @param classPath
     * @return java.lang.Object
     * @author codewsq
     * @date 2021/7/19 0019 14:01
     */
    public Object getInstance(String classPath) {
        Object o = null;
        try {
            Class<?> clazz = Class.forName(classPath);
            o = clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return o;
    }
}
